﻿using System;
using Internal.Runtime.Models;

namespace Runtime.Models {

    /// <summary>
    /// 连接中的远程数据
    /// </summary>
    public interface IDFR_NetModel : IDFR_Model {

        public static readonly DateTime START = DateTime.Parse("1970-1-1").ToLocalTime();

        /// <summary>
        /// 登录服务器时取得的时间戳(毫秒)
        /// </summary>
        long TimeTicks { get; }

        /// <summary>
        /// 与服务器之间的时间差
        /// </summary>
        TimeSpan TimeSpan { get; }

        /// <summary>
        /// 服务器当前时间,由本地时间与服务器时间差计算而来的服务器当前时间
        /// </summary>
        DateTime Now { get; }

        /// <summary>
        /// 服务器当前时间,由本地时间与服务器时间差计算而来的服务器当前时间
        /// </summary>
        TimeSpan NowTimeSpan { get; }

        /// <summary>
        /// 服务器时间的今天0点
        /// <seealso cref="Now"/>
        /// </summary>
        DateTime Today { get; }

        /// <summary>
        /// 服务器时间的明天0点
        /// </summary>
        /// <seealso cref="Now"/>
        DateTime Tomorrow { get; }

        /// <summary>
        /// 连接至服务器的时间
        /// </summary>
        TimeSpan Start { get; }
    }

    [Implement(typeof(IDFR_NetModel))]
    internal sealed class DFR_NetModel : DFR_Model, IDFR_NetModel, IDFR_NetModelInternal {

        private long m_TimeTicks;
        long IDFR_NetModel.TimeTicks => m_TimeTicks;

        public TimeSpan TimeSpan { get; private set; }

        public DateTime Now => DateTime.Now + TimeSpan;

        public TimeSpan NowTimeSpan => Now - IDFR_NetModel.START;

        public DateTime Today => Now.Date;

        public DateTime Tomorrow => Now.Date.AddDays(1);

        public TimeSpan Start { get; private set; }

        private long m_ClientTimeTicks;

        void IDFR_NetModelInternal.SetClientTimeTicks() {
            m_ClientTimeTicks = DateTime.Now.Ticks;
        }

        void IDFR_NetModelInternal.SetTimeTicks(long time) {
            m_TimeTicks = time;
            var clientTime = new DateTime(m_ClientTimeTicks) - IDFR_NetModel.START;
            Start = TimeSpan.FromMilliseconds(m_TimeTicks);
            TimeSpan = Start - clientTime;
            UnityEngine.Debug.Log($"当前服务器时间: {Now}");
        }
    }
}

namespace Internal.Runtime.Models {

    public interface IDFR_NetModelInternal {

        void SetClientTimeTicks();

        void SetTimeTicks(long time);
    }
}
